#include "Item.h"
#include "XmlDefines.h"



Item::Item(QVariant type, QObject* parent) : QObject(parent)
{
    data = new Data;
    setType(type);
}



Item::Item(const Item& other)
    : data(other.data)
{
}



int Item::id() const
{
    return data->id;
}


void Item::regenId()
{
    data->id = ID(data->name, data->type.toString());
}

QString Item::name() const
{
    return data->name;
}



void Item::setName(const QString& name)
{
    if (data->name == name) return;

    data->name = name;

    regenId();
    emit sigChanged();
}



QVariant Item::value() const
{
    return data->value;
}



void Item::setValue(const QVariant& value)
{
    if (data->value == value) return;

    data->value = value;
    emit sigChanged();
}



QString Item::desc() const
{
    return data->desc;
}



void Item::setDesc(const QString& desc)
{
    if (data->desc == desc) return;

    data->desc = desc;
    emit sigChanged();
}



QVariant Item::type() const
{
    return data->type;
}



void Item::setType(const QVariant& type)
{
    if (data->type == type) return;
    data->type = type;

    regenId();
    emit sigChanged();
}



QDomElement Item::toXmlElem(QDomElement& elem) const
{
    if (elem.isNull()) return elem;

    elem.setAttribute(g_ATTR_NAME, name());

    if (!value().isNull()) elem.setAttribute(g_ATTR_VALUE, value().toString());



    QDomDocument doc = elem.ownerDocument();

    QDomElement desc_elem = elem.firstChildElement(g_ELEM_DESC);
    if (desc_elem.isNull())
    {
        if (doc.isNull()) return elem;

        desc_elem = doc.createElement(g_ELEM_DESC);
        if (desc_elem.isNull()) return elem;

        elem.appendChild(desc_elem);
    }

    QDomText desc_text = desc_elem.firstChild().toText();
    if (desc_text.isNull())
    {
        desc_text = doc.createTextNode(desc());
        desc_elem.appendChild(desc_text);
    }

    desc_text.setData(desc());


    return elem;
}



void Item::fromXmlElem(QDomElement& elem)
{
    setName(elem.attribute(g_ATTR_NAME,"Unknown name"));
    setValue(elem.attribute(g_ATTR_VALUE, "0"));

    QDomElement desc = elem.firstChildElement(g_ELEM_DESC);
    if (desc.isNull()) return;

    setDesc(desc.text());
}



